package com.dsg.workflow;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dsg.entity.apply.DsgApplyBill;
import com.dsg.entity.apply.DsgApplyCar;
import com.dsg.entity.apply.DsgApplyCard;
import com.dsg.entity.apply.DsgApplyPay;
import com.dsg.entity.approve.DsgApproveCase;
import com.dsg.service.apply.IDsgApplyCarService;
import com.dsg.service.apply.IDsgApplyCusService;
import com.dsg.service.apply.IDsgApplyPayService;
import com.dsg.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 新增繳款資料
 */
@Service
public class WorkflowService30 extends AbstractWorkflowService {
//    @Autowired
//    IDsgApplyCarService carService;
//    @Autowired
//    IDsgApplyCusService cusService;
    @Autowired
    IDsgApplyPayService payService;
    @Autowired
    WorkflowEngine engine;

    @Override
    protected String recalculateNodeName(DsgApplyBill bill) {
        return NODE_CS_APPLY;
    }

    @Override
    protected Set getConditionalNodeSet(DsgApplyBill bill) {
        Set<String> conditionalNodeSet = new HashSet<>();
        if (Constant.PAY_TYPE_ATP.equals(bill.getPayType())) {
            conditionalNodeSet.add(NODE_DDA);
        } else {
            conditionalNodeSet.add(NODE_DEDUCT_ONE);
        }
        return conditionalNodeSet;
    }

    @Override
    protected boolean canGoOn(DsgApplyBill bill) throws Exception {
        boolean payAudit = payService.payAuditAll(bill);
        return payAudit;
    }

    @Override
    public void deductOneFillBack(DsgApproveCase approveCase) {
        fillBack(approveCase);
    }

    @Override
    public void ddaFillBack(DsgApproveCase approveCase) {
        fillBack(approveCase);
    }

    private void fillBack(DsgApproveCase approveCase) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", approveCase.getAppNo());
        DsgApplyPay applyPay = payService.getOne(wrapper);
//        wrapper = new QueryWrapper();
//        wrapper.
//        List<DsgApplyCar> carList = carService.listByIds(Arrays.asList(applyPay.getCarOids().split(",")));
//        List<String> carOids = carList.stream().map(e -> e.getOid()).collect(Collectors.toList());
//        wrapper = new QueryWrapper();
//        wrapper.eq("CAR_ID", Arrays.asList(applyPay.getCarOids().split(",")));
        LambdaUpdateWrapper<DsgApplyCard> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(e -> e.getCarId(), Arrays.asList(applyPay.getCarOids().split(",")));
        DsgApplyCard card = new DsgApplyCard();
        card.setPayId(applyPay.getOid());
        card.setMainPayId(applyPay.getOid());
        cardService.update(card, updateWrapper);
    }
}
